function neighbors = bvqx_srf_parseneighbors(fid, numvtx)
% bvqx_srf_parseneighbors  - parse neighbors from SRF file
%
% FORMAT:       neighbors = bvqx_srf_parseneighbors(fid, numvtx)
%
% Input fields:
%
%       fid         input file fid (fopen)
%       numvtx      number of vertices
%
% Output fields
%
%       neighbors   Nx2 cell array with content
%        {N, 1}     1x1 double, number of neighbors for vertex(N)
%        {N, 2}     1xN double, list of neighbors
%
% See also BVQXfile, bffio
%
% Note: this function uses a compiled function, bvqx_srf_parseneighborsc.

% Version:  v0.7g
% Build:    9101521
% Date:     Oct-15 2009, 3:44 PM CEST
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin < 2 || ...
   ~isa(fid, 'double') || ...
    isempty(fid) || ...
   ~isreal(fid) || ...
   ~any(fopen('all') == fid(1)) || ...
   ~isa(numvtx, 'double') || ...
    isempty(numvtx) || ...
   ~isreal(numvtx) || ...
    isnan(numvtx(1)) || ...
    isinf(numvtx(1)) || ...
    numvtx(1) < 3
    error( ...
        'BVQXtools:BadArgument', ...
        'Bad or missing argument.' ...
    );
end

% try
try
    
    % get current position
    cpos = ftell(fid);

    % get remainder of contents
    vcont = fread(fid, [1, Inf], '*uint32');
    vlen  = length(vcont);

    % sanity check, in a mesh triangle vertices MUST have at least 3 neighbors
    if vlen < (4 * numvtx)
        error('Too few DWORDs left.');
    end
    
    % get neighbors
    [neighbors, skip] = bvqx_srf_parseneighborsc(vcont, numvtx);

    % seek to good position
    fseek(fid, cpos + 4 * skip, -1);

catch
    error( ...
        'BVQXtools:BadFileOrContent', ...
        'Reading of file failed with: ''%s''.', ...
        lasterr ...
    );
end
